import classNames from "classnames";
import { useDispatch } from "react-redux";
import { delTodo, toggleDone, updateTodo } from "../store/actions/todos";
import { useEffect, useState } from "react";
import { useRef } from "react";

const TodoItem = ({ id, text, done }) => {
  const dispatch = useDispatch();
  // 控制编辑状态
  const [showEdit, setShowEdit] = useState(false);
  // 创建ref
  const inputRef = useRef(null);
  // 通过副作用来监听showEdit
  useEffect(() => {
    if (showEdit === true) {
      inputRef.current.focus();
    }
  }, [showEdit]);

  // 文本框默认值就是text
  const [todoName, setTodoName] = useState(text);
  // 按键事件
  const onKeyDown = (e) => {
    if (e.keyCode !== 13) return;
    if (todoName.trim() === "") return;
    dispatch(updateTodo(id, todoName));
    setShowEdit(false)
  };
  // 失去焦点
  const onBlur = () => {
    if (todoName.trim() === "") return;
    dispatch(updateTodo(id, todoName));
    setShowEdit(false);
  };

  return (
    <li
      className={classNames({
        completed: done,
        editing: showEdit,
      })}
    >
      <div className="view">
        <input
          className="toggle"
          type="checkbox"
          checked={done}
          onChange={(e) => dispatch(toggleDone(id, e.target.checked))}
        />
        <label onDoubleClick={() => setShowEdit(true)}>{text}</label>
        <button
          className="destroy"
          onClick={() => dispatch(delTodo(id))}
        ></button>
      </div>
      {/* 输入框 */}
      <input
        ref={inputRef}
        className="edit"
        onBlur={onBlur}
        value={todoName}
        onChange={(e) => setTodoName(e.target.value)}
        onKeyDown={onKeyDown}
      />
    </li>
  );
};

export default TodoItem;
